<template>
    <div class="jianzhan-content">
        <Crumb name="发运/Shipping"></Crumb>

        <div class="content">
            <el-button type="primary" size="small" icon="el-icon-plus" @click="openAdd"
                       v-if="urlAvailible('shanqi-delivery-operate')">发运
            </el-button>
            <el-button type="primary" size="small" icon="el-icon-download" @click="download"
                       v-if="urlAvailible('shanqi-delivery-operate')">{{$t('download')}}
            </el-button>
            <!--<a class="link-btn" target="_blank" href="http://static.sh-inline.com/模版.xlsx">模版下载</a>-->
            <el-input v-model="key" style="display: inline-block;width: 200px;margin-left: 20px;" size="small"
                      placeholder="Search Contract"></el-input>
            <el-input v-model="key1" style="display: inline-block;width: 200px;margin-left: 20px;" size="small"
                      placeholder="Search Ship"></el-input>
            <div class="total" style="float: right;margin-right: 30px;">总金额: {{total}}</div>
            <div class="table-wrapper">
                <el-table
                        :data="list"
                        border
                        stripe
                        style="width: 100%">
                    <el-table-column
                            type="index"
                            label="序号/No"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="sendGoodsContract"
                            label="发运合同/Shipping Contract"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="boxNumber"
                            label="件数/Box Number">
                    </el-table-column>
                    <el-table-column
                            prop="sendTotalMoney"
                            label="发运金额/Shipping Amount">
                    </el-table-column>
                    <el-table-column
                            prop="leaveFactoryDateStr"
                            label="出厂日期/Manufacture Date">
                    </el-table-column>
                    <el-table-column
                            prop="port"
                            label="港口/Port">
                    </el-table-column>
                    <el-table-column
                            prop="shipInformation"
                            label="船次/Ship Info">
                    </el-table-column>
                    <el-table-column
                            prop="boxList"
                            label="箱单/Packing List">
                        <template slot-scope="scope">
                            <a v-for="item in (scope.row.boxList ? scope.row.boxList.split(','):[])" :key="item"
                               :href="item" target="_blank" style="display: block">{{item | getFileName}}</a>
                        </template>
                    </el-table-column>
                    <el-table-column
                    >
                        <template slot-scope="scope">
                            <div>
                                <el-button type="primary" icon="el-icon-edit" size="small" @click="openEdit(scope.row)">
                                    Edit
                                </el-button>
                            </div>
                            <div>
                                <el-button type="primary" icon="el-icon-edit" size="small" @click="print1(scope.row)"
                                           style="margin-left: 0;margin-top: 10px;">Print1
                                </el-button>
                            </div>
                            <div>
                                <el-button type="primary" icon="el-icon-edit" size="small" @click="print2(scope.row)"
                                           style="margin-left: 0;margin-top: 10px;">Print2
                                </el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
        <el-dialog
                title="添加发运信息/Add Shipping Information"
                :visible.sync="dialogVisible"
                width="80%"
        >
            <el-form ref="form" :model="delivery" label-width="200px" style="text-align: left">
                <el-form-item label="发运合同/Shipping Contract">
                    <el-select
                            v-model="delivery.consignmentId"
                            filterable
                            @change="contractChange"
                            placeholder="Please select Contract"
                            size="small"
                            class="input">
                        <el-option
                                v-for="item in consignmentList"
                                :key="item.id"
                                :label="item.contractNumber"
                                :value="item.id">
                        </el-option>
                    </el-select>
                    <el-select v-model="delivery.times"
                               @change="batchChange"
                               placeholder="Please Select Delivery frequency"
                               size="small"
                               class="input">
                        <el-option
                                label="A"
                                value="A">
                        </el-option>
                        <el-option
                                label="A2"
                                value="A2">
                        </el-option>
                        <el-option
                                label="B"
                                value="B">
                        </el-option>
                        <el-option
                                label="B2"
                                value="B2">
                        </el-option>
                        <el-option
                                label="C"
                                value="C">
                        </el-option>
                        <el-option
                                label="C2"
                                value="C2">
                        </el-option>
                        <el-option
                                label="D"
                                value="D">
                        </el-option>
                        <el-option
                                label="D2"
                                value="D2">
                        </el-option>
                        <el-option
                                label="E"
                                value="E">
                        </el-option>
                        <el-option
                                label="F"
                                value="F">
                        </el-option>
                        <el-option
                                label="G"
                                value="G">
                        </el-option>
                        <el-option
                                label="H"
                                value="H">
                        </el-option>
                    </el-select>
                    <span>{{sendGoodsContract}}</span>
                    <el-select v-model="mixConsignmentId" filterable clearable placeholder="混合箱单号" size="small"
                               @change="mixChange">
                        <el-option
                                v-for="item in consignmentList"
                                :key="item.id"
                                :label="item.contractNumber"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="件数/Box Number">
                    <el-input v-model="delivery.boxNumber" placeholder="PCS" size="small"></el-input>
                </el-form-item>
                <el-form-item label="发运金额/Shipping Amount">
                    <el-currency-input v-model="delivery.sendTotalMoney" placeholder="Delivery Price"
                                       size="small"></el-currency-input>
                </el-form-item>
                <el-form-item label="港口/Port">
                    <el-select v-model="delivery.port" placeholder="Port" size="small">
                        <el-option label="SH" value="SH"></el-option>
                        <el-option label="ZJG" value="ZJG"></el-option>
                        <el-option label="DHL" value="DHL"></el-option>
                        <el-option label="NB" value="NB"></el-option>
                        <el-option label="DL" value="DL"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="出厂日期/Manufacture Date">
                    <el-date-picker v-model="delivery.leaveFactoryDateStr" value-format="yyyy-MM-dd"
                                    placeholder="Factory Date" size="small"></el-date-picker>
                </el-form-item>
                <!--<div style="margin-bottom: 20px" v-if="urlAvailible('shanqi-delivery-operate')">-->
                    <!--<div><label for="file" class="label-btn">上传明细/Upload File</label></div>-->
                    <!--<input type="file" @change="fileChange" id="file" v-show="false" ref="file">-->
                <!--</div>-->
                <div style="margin-bottom: 20px" v-if="urlAvailible('shanqi-delivery-operate')">
                    <div ref="drag" ondragstart="return false" style="border: 1px dashed #ddd">
                        <label for="file1" class="label-btn">上传箱单/Upload Box List</label>
                    </div>
                    <input type="file" @change="fileChange1" id="file1" multiple v-show="false" ref="file1">
                    <div v-for="item in delivery.boxList" :key="item">{{item | getFileName}}</div>
                </div>
                <div class="table">
                    <el-table
                            :data="partList"
                            stripe
                            show-summary
                            border
                            height="500px"
                            style="width:95%">
                        <el-table-column
                                prop="partsNum"
                                label="配件编号/Part No"
                        >
                        </el-table-column>
                        <el-table-column
                                prop="denomination"
                                label="中文"
                                width="180">
                        </el-table-column>
                        <el-table-column
                                prop="designation"
                                label="English">
                        </el-table-column>
                        <el-table-column
                                prop="quantity"
                                label="Qty">
                        </el-table-column>
                        <el-table-column
                                prop="unit"
                                label="unit">
                        </el-table-column>
                        <el-table-column
                                prop="salesUnitPrice"
                                label="单价/Unit Price">
                            <!--<template slot-scope="scope">-->
                            <!--<span>{{scope.row.salesUnitPrice}}</span>-->
                            <!--&lt;!&ndash;<span :class="scope.row.priceStatus === 1 ? 'warning':''">{{scope.row.salesUnitPrice}}</span>&ndash;&gt;-->
                            <!--&lt;!&ndash;<div v-if="scope.row.priceStatus === 1 ">Excel中单价与系统不一致</div>&ndash;&gt;-->
                            <!--</template>-->
                        </el-table-column>
                        <el-table-column
                                prop="totalLinePrice"
                                label="总价/Total Price">
                            <!--<template slot-scope="scope">-->
                            <!--<span>{{scope.row.quantity * scope.row.salesUnitPrice}}</span>-->
                            <!--</template>-->
                        </el-table-column>
                        <el-table-column
                                prop="differentConsignmentOrderDesc"
                                label="Mix Packing"
                        >
                        </el-table-column>
                    </el-table>
                </div>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">Cancel</el-button>
                <el-button type="primary" @click="submitForm"
                           v-if="urlAvailible('shanqi-delivery-operate')">Confirm</el-button>
            </span>
        </el-dialog>
        <print3 :dialogVisible="print3Visible"
                :boxList="boxList"
                :total="boxTotal"
                @close="print3Visible = false"> </print3>
        <print4 :dialogVisible="print4Visible"
                :boxList="boxList"
                :total="boxTotal"
                @close="print4Visible = false"> </print4>
    </div>
</template>

<script>
    import Crumb from '../../components/common/crumb'
    import {
        getContractList,
        getDeliveryList,
        addDelivery,
        modDelivery,
        getDeliveryDetail,
        uploadPackageList,
        uploadSendingList
    } from "../../api/contract";
    import {getAllPackListDetail, getAllPackListReport} from "../../api/shanxi";
    import {ERROR_OK} from "../../util/config";
    import {baseURL, getFileName} from "../../util";
    import print3 from './print3'
    import print4 from './print4'
    import authMixins from '../../util/authMixins'

    export default {
        name: "delivery",
        mixins: [authMixins],
        data() {
            return {
                boxList: [],
                boxTotal: {},
                print3Visible: false,
                print4Visible: false,
                key: '',
                key1: '',
                deliveryList: [],
                partList: [],
                total: 0,
                mixConsignmentId: '',
                delivery: {
                    consignmentId: '',
                    contractNumber: '',
                    times: '',
                    boxNumber: '',
                    sendTotalMoney: 0,
                    port: '',
                    leaveFactoryDateStr: '',
                    boxList: [],
                    sendGoodsDetails: ''
                },
                dialogVisible: false
            }
        },

        computed: {
            sendGoodsContract() {
                return this.delivery.contractNumber + '-' + this.delivery.times
            },
            list(){
                return this.deliveryList.filter(
                    item => {
                        return item.sendGoodsContract.toLowerCase().includes(this.key.toLowerCase())
                    }).filter(item => {
                        return item.shipInformation ? item.shipInformation.toLowerCase().includes(this.key1.toLowerCase()) : true
                    })
            }
        },
        filters: {
            getFileName(name) {
                return getFileName(name)
            }
        },
        created() {
            this.getConsignmentList();
            this.getDeliveryList()
        },
        methods: {
            // 文件下载
            download(){
                window.open(baseURL + '/send_goods/manage/send_basic_information.file')
            },
            async getBoxDetail(consignmentId, batch) {
                const {status, data,msg} = await getAllPackListDetail(consignmentId, batch);
                if (status === ERROR_OK) {
                    return Promise.resolve(data);
                } else {
                    this.$message.error(msg);
                    return Promise.resolve([]);
                }
            },
            print1(row) {
                const batch = row.sendGoodsContract.substr(row.sendGoodsContract.length - 1, 1);
                this.getBoxReport(row.consignmentId, batch);
                this.print3Visible = true;
            },
            print2(row) {
                const batch = row.sendGoodsContract.substr(row.sendGoodsContract.length - 1, 1);
                this.getBoxReport(row.consignmentId, batch);
                this.print4Visible = true;
            },
            async getBoxReport(consignmentOrderId, batch) {
                const {status, data} = await getAllPackListReport({consignmentOrderId, batch});
                if (status === ERROR_OK) {
                    this.boxList = data.packingOrders;
                    this.boxTotal = {
                        totalGrossWeight: data.totalGrossWeight,
                        totalNetWeight: data.totalNetWeight,
                        totalVolume: data.totalVolume
                    }
                } else {
                    this.boxList = [];
                    this.boxTotal = {}
                }
            },
            inialDrag() {
                const drag = this.$refs.drag;
                drag.ondragleave = e => {
                    e.stopPropagation();
                    e.preventDefault()
                };
                drag.ondrop = async e => {
                    e.preventDefault();
                    drag.style.border = '1px dashed #ddd'
                    const files = e.dataTransfer.files;  // 获取文件对象
                    if (files.length < 1) {
                        return;  // 检测是否有文件拖拽到页面
                    }
                    const formData = new FormData();
                    Array.prototype.forEach.call(files, item => {
                        formData.append('exFiles', item)
                    });
                    const {status, data} = await uploadPackageList(formData);
                    if (status === 0) {
                        this.$set(this.delivery, 'boxList', data.file_path)
                    }
                };
                drag.ondragenter = e => {
                    e.stopPropagation();
                    e.preventDefault();
                    drag.style.border = '1px dashed #483eff'
                };
                drag.ondragover = e => {
                    e.stopPropagation();
                    e.preventDefault()
                }
            },
            async submitForm() {
                const {id, consignmentId, boxNumber, sendTotalMoney, port, leaveFactoryDateStr} = this.delivery;
                let {boxList} = this.delivery;
                boxList = boxList.join(',');
                let sendGoodsDetails = this.partList.map(item => {
                    return {
                        partsId: item.partsId,
                        quantity: item.quantity,
                        salesUnitPrice: item.salesUnitPrice,
                        unit: item.unit,
                        consignmentOrderId: item.consignmentOrderId,
                        packingOrderId: item.packingOrderId,
                    }
                });
                sendGoodsDetails = JSON.stringify(sendGoodsDetails);
                const sendGoodsContract = this.sendGoodsContract;

                if (id) {
                    const {status, msg} = await modDelivery(
                        {
                            id,
                            sendGoodsContract,
                            consignmentId,
                            boxNumber,
                            sendTotalMoney,
                            port,
                            leaveFactoryDateStr,
                            boxList,
                            sendGoodsDetails,
                            additionalContract: this.mixConsignmentId
                        });
                    if (status === ERROR_OK) {
                        this.getDeliveryList();
                        this.$notify.success('修改发运合同成功');
                        this.dialogVisible = false;
                        this.clear()
                    } else {
                        this.$notify.error(msg)
                    }
                } else {
                    const {status, msg} = await addDelivery({
                        sendGoodsContract,
                        consignmentId,
                        boxNumber,
                        sendTotalMoney,
                        port,
                        leaveFactoryDateStr,
                        boxList,
                        sendGoodsDetails,
                        additionalContract: this.mixConsignmentId
                    });
                    if (status === ERROR_OK) {
                        this.getDeliveryList();
                        this.$notify.success('添加发运合同成功');
                        this.dialogVisible = false;
                        this.clear()
                    } else {
                        this.$notify.error(msg)
                    }
                }


            },
            clear() {
                this.delivery = {
                    consignmentId: '',
                    contractNumber: '',
                    times: '',
                    boxNumber: '',
                    sendTotalMoney: 0,
                    port: '',
                    leaveFactoryDateStr: '',
                    boxList: [],
                    sendGoodsDetails: ''
                };
                this.partList = []
            },
            async openEdit(row) {
                const {status, data} = await getDeliveryDetail(row.id);
                if (status === ERROR_OK) {
                    this.delivery = data;
                    const boxList = data.boxList ? data.boxList.split(',') : [];
                    this.$set(this.delivery, 'boxList', boxList);
                    this.$set(this.delivery, 'contractNumber', data.sendGoodsContract.substr(0, data.sendGoodsContract.length - 2));
                    this.$set(this.delivery, 'times', data.sendGoodsContract.substr(data.sendGoodsContract.length - 1, 1));
                    this.partList = data.sendGoodsDetailVos ? data.sendGoodsDetailVos.map(item => {
                        return {
                            ...item,
                            partsNum: item.partsNumber,
                            quantity: item.sendQuantity,
                            salesUnitPrice: item.purchasePrice
                        }
                    }) : []
                }
                this.dialogVisible = true;
                this.$nextTick(() => {
                    this.inialDrag()
                });
            },
            openAdd() {
                this.dialogVisible = true;
                this.clear();
                this.$nextTick(() => {
                    this.inialDrag()
                });
            },
            async fileChange(e) {
                const formData = new FormData();
                Array.prototype.forEach.call(e.target.files, item => {
                    formData.append('exFiles', item)
                });
                const {status, data} = await uploadSendingList(formData);
                if (status === 0) {
                    this.partList = data.data;
                }
                this.$refs.file.value = '';
            },
            async fileChange1(e) {
                const formData = new FormData();
                Array.prototype.forEach.call(e.target.files, item => {
                    formData.append('exFiles', item)
                });
                const {status, data} = await uploadPackageList(formData);
                if (status === 0) {
                    this.$set(this.delivery, 'boxList', data.file_path)
                }
            },
            async getDeliveryList() {
                const {status, data, msg} = await getDeliveryList();
                if (status === ERROR_OK) {
                    this.deliveryList = data
                    this.total = msg
                }
            },
            async contractChange(key) {
                const target = this.consignmentList.find(item => item.id === key);
                if (target) {
                    this.delivery.contractNumber = target.contractNumber
                }
                if (this.delivery.consignmentId && this.delivery.times) {
                    const data = await this.getBoxDetail(this.delivery.consignmentId, this.delivery.times);
                    this.partList = data.packing_detail;
                    this.$set(this.delivery,'boxNumber',data.total_box);
                    this.mixConsignmentId = '';
                }
            },
            async batchChange() {
                if (this.delivery.consignmentId && this.delivery.times) {
                    const data = await this.getBoxDetail(this.delivery.consignmentId, this.delivery.times);
                    this.partList = data.packing_detail;
                    this.$set(this.delivery,'boxNumber',data.total_box);
                    this.mixConsignmentId = '';
                }
            },
            async mixChange(v) {
                if (!v) {
                    this.partList = this.partList.filter(item => item.consignmentOrderId === this.delivery.consignmentId);
                    return false;
                }
                if (this.delivery.times) {
                    const partList = this.partList.filter(item => item.consignmentOrderId === this.delivery.consignmentId)
                    const data = await this.getBoxDetail(this.mixConsignmentId, this.delivery.times);
                    this.partList = partList.concat(data.packing_detail);
                } else {
                    this.$message.error('请选择发运批次');
                    this.mixConsignmentId = '';
                }
            },
            async getConsignmentList() {
                const {status, data} = await getContractList();
                if (status === ERROR_OK) {
                    this.consignmentList = data ? data : [];
                } else {
                    this.consignmentList = [];
                }
            }
        },
        watch:{
            // 如果配件列表变化,重新计算总金额
          partList(list){
              let total = 0;
             if(list.length) {
                 list.forEach(item=>{
                     total += item.totalLinePrice
                 });
                 console.log(total);
                 total = (total / 1.1).toFixed(2)
                 this.$set(this.delivery,'sendTotalMoney',total)
             }else {
                 this.$set(this.delivery,'sendTotalMoney',0)

             }
          }
        },
        components: {
            Crumb, print3, print4
        }
    }
</script>

<style scoped lang="scss">
    @import '../../css/mixins';
    @import '../../css/variable';

    .content {
        @include content
    }

    .link-btn {
        @include linkBtn
    }

    .label-btn {
        cursor: pointer;
        height: 30px;
        line-height: 30px;
        text-align: center;
        color: white;
        background-color: #409eff;
        border-radius: 3px;
        padding: 5px 15px;
        display: block;
        width: 120px;
    }
</style>